package com.coin900.coin.cmd;

import com.coin900.coin.cmd.CmdSign;
import com.coin900.coin.code.CmdCode;
import com.coin900.coin.code.RespCode;
import com.value.exception.AppException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Unibon
 * <p/>
 * Copyright (c) 2012 YouPeng ValueSoft Inc., All rights reserved.
 * <p/>
 * This software is the confidential and proprietary information of
 * ValueSoft Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with ValueSoft.com.
 * <p/>
 * Revision History
 * Date      		Programmer       Notes
 * 2014/12/22   	     stone		     Initial
 * *********************************************************************
 */
@Component
public class Scheduler {
    private final static Logger logger = LoggerFactory.getLogger(Scheduler.class);
    private Map<String, ICommand> cmdMap = new HashMap<>();

    public CmdSign schedule(HttpServletRequest request, CmdSign sign) throws Exception {
        String cmdCode = sign.getCmdCode();
        if (StringUtils.isEmpty(sign.getCmdVersion())) {
            sign.setCmdVersion("1");
        }
        ICommand cmd = this.cmdMap.get(cmdCode + sign.getCmdVersion());
        if (cmd != null) {
            CmdSign respSign;
            sign.startExe();
            respSign = cmd.execute(request, sign);
            sign.endExe();
            return respSign;
        } else {
            CmdSign respSign = new CmdSign(CmdCode.ERROR_POST,null,RespCode.CMD_UN_REGIST);
            respSign.setToken(sign.getToken());
            respSign.setMsg(cmdCode + "命令未注册");
            logger.error(respSign.getMsg());
            return respSign;
        }
    }



    public CmdSign execute(CmdSign sign) throws Exception {
        String cmdCode = sign.getCmdCode();
        if (StringUtils.isEmpty(sign.getCmdVersion())) {
            sign.setCmdVersion("1");
        }
        ICommand cmd = this.cmdMap.get(cmdCode + sign.getCmdVersion());
        if (cmd != null) {
            CmdSign respSign = cmd.execute(null, sign);
            return respSign;
        } else {
            CmdSign respSign = new CmdSign(CmdCode.ERROR_POST,null,RespCode.CMD_UN_REGIST);
            respSign.setMsg(cmdCode + "命令未注册");
            return respSign;
        }
    }

    public void register(String code, ICommand cmd) {
        if (this.cmdMap.containsKey(code)) {
            throw new AppException("重复注册cmd:" + code);
        }
        cmdMap.put(code, cmd);
    }

}
